<template>
  <div class="order-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">订单管理</span>
          <div class="right-button">
            <el-button type="primary" :icon="Plus" @click="handleAdd"> 新增 </el-button>
            <el-button type="warning" :icon="Download" @click="handleExport"> 导出 </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item label="订单编号" prop="orderCode">
          <el-input
            v-model="queryParams.orderCode"
            placeholder="请输入订单编号"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="项目" prop="projectId">
          <el-select
            v-model="queryParams.projectId"
            placeholder="请选择项目"
            clearable
            style="width: 220px"
          >
            <el-option
              v-for="item in projectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId">
          <el-select
            v-model="queryParams.supplierId"
            placeholder="请选择供应商"
            clearable
            style="width: 220px"
          >
            <el-option
              v-for="item in supplierOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table v-loading="loading" :data="orderList" style="width: 100%" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="orderCode" label="订单编号" align="center" width="120" />
        <el-table-column
          prop="projectName"
          label="项目名称"
          align="center"
          min-width="150"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="supplierName"
          label="供应商名称"
          align="center"
          min-width="150"
          :show-overflow-tooltip="true"
        />
        <el-table-column prop="startDate" label="开始日期" align="center" width="120" />
        <el-table-column prop="endDate" label="结束日期" align="center" width="120" />
        <el-table-column prop="settlementCycleName" label="结算周期" align="center" width="100" />
        <el-table-column prop="totalAmount" label="订单金额" align="center" width="120">
          <template #default="scope">
            {{ formatAmount(scope.row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              link
              :icon="Edit"
              @click="handleUpdate(scope.row)"
              >编辑</el-button
            >
            <el-button size="small" type="primary" link :icon="View" @click="handleView(scope.row)"
              >查看</el-button
            >
            <el-popconfirm
              :title="`是否确认删除订单'${scope.row.orderCode}'?`"
              @confirm="handleDelete(scope.row)"
            >
              <template #reference>
                <el-button size="small" type="danger" link :icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @current-change="val => (queryParams.pageNum = val)"
          @size-change="val => (queryParams.pageSize = val)"
          @update:current-page="getList"
        />
      </div>
    </el-card>

    <!-- 订单表单组件 -->
    <OrderForm
      v-if="dialog.visible"
      v-model="dialog.visible"
      :title="dialog.title"
      :order="currentOrder"
      :project-options="projectOptions"
      :supplier-options="supplierOptions"
      @success="getList"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted, nextTick } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { Plus, Download, Search, Refresh, Edit, View, Delete } from "@element-plus/icons-vue";
import {
  getOrderList,
  getOrderInfo,
  deleteOrder,
  exportOrder,
  getProjectOptions,
  getSupplierOptions
} from "@/api/attendance/order";
import { OrderVO, OrderQuery } from "@/types/attendance/order";
import { handleLoadError } from "@/utils/error-handler";
import { openTagByName } from "@/utils/tag-utils";

// 组件导入
import OrderForm from "./components/OrderForm.vue";

export default defineComponent({
  name: "OrderManagement",
  components: {
    OrderForm
  },
  setup() {
    const router = useRouter();

    // 状态选项
    const statusOptions = [
      { value: "0", label: "进行中" },
      { value: "1", label: "已完成" },
      { value: "2", label: "已取消" }
    ];

    // 获取状态标签类型
    const getStatusType = (status: string): "success" | "warning" | "info" | "danger" => {
      const map: Record<string, "success" | "warning" | "info" | "danger"> = {
        "0": "info", // 进行中 - 使用info
        "1": "success", // 已完成
        "2": "danger" // 已取消
      };
      return map[status] || "info";
    };

    // 金额格式化
    const formatAmount = (amount: number | undefined) => {
      if (amount === undefined) return "0.00";
      return amount.toFixed(2) + " 元";
    };

    // 项目选项
    const projectOptions = ref<Array<{ value: number; label: string }>>([]);

    // 供应商选项
    const supplierOptions = ref<Array<{ value: number; label: string }>>([]);

    // 查询参数
    const queryParams = reactive<OrderQuery>({
      orderCode: "",
      projectId: undefined,
      supplierId: undefined,
      status: "",
      pageNum: 1,
      pageSize: 10
    });

    // 表格数据
    const orderList = ref<OrderVO[]>([]);
    const loading = ref(false);
    const total = ref(0);

    // 当前选中的订单
    const currentOrder = ref<OrderVO>({} as OrderVO);

    // 弹窗状态
    const dialog = reactive({
      title: "",
      visible: false
    });

    // 表单引用
    const queryRef = ref<FormInstance>();

    // 获取订单列表
    const getList = async () => {
      loading.value = true;
      try {
        const params = {
          ...queryParams,
          orderCode: queryParams.orderCode?.trim() || undefined,
          projectId: queryParams.projectId || undefined,
          supplierId: queryParams.supplierId || undefined,
          status: queryParams.status || undefined
        };

        const res = await getOrderList(params);

        // 判断响应格式并兼容处理
        if (res.data && Array.isArray(res.data.rows)) {
          // 标准格式
          orderList.value = res.data.rows;
          total.value = res.data.total;
        } else {
          // 格式不符合预期
          console.warn("API返回数据格式不符合预期", res);
          orderList.value = [];
          total.value = 0;
          ElMessage.warning("获取订单数据格式异常，请联系管理员");
        }
      } catch (error) {
        console.error("获取订单列表失败", error);
        handleLoadError(error, "订单列表");
        orderList.value = [];
        total.value = 0;
      } finally {
        loading.value = false;
      }
    };

    // 获取项目选项
    const fetchProjectOptions = async () => {
      try {
        const res = await getProjectOptions();
        if (res.data) {
          projectOptions.value = res.data.map(
            (item: { projectId: number; projectName: string }) => ({
              value: item.projectId,
              label: item.projectName
            })
          );
        }
      } catch (error) {
        handleLoadError(error, "项目选项");
      }
    };

    // 获取供应商选项
    const fetchSupplierOptions = async () => {
      try {
        const res = await getSupplierOptions();
        if (res.data) {
          supplierOptions.value = res.data.map(
            (item: { supplierId: number; supplierName: string }) => ({
              value: item.supplierId,
              label: item.supplierName
            })
          );
        }
      } catch (error) {
        handleLoadError(error, "供应商选项");
      }
    };

    // 搜索按钮操作
    const handleQuery = () => {
      queryParams.pageNum = 1;
      getList();
    };

    // 重置按钮操作
    const resetQuery = () => {
      if (queryRef.value) {
        queryRef.value.resetFields();
        queryParams.pageNum = 1;
        queryParams.pageSize = 10;
      }
      handleQuery();
    };

    // 新增按钮操作
    const handleAdd = () => {
      dialog.title = "添加订单";
      // 先关闭对话框，强制组件重新渲染
      dialog.visible = false;

      // 重置数据
      currentOrder.value = {} as OrderVO;

      // 使用nextTick确保DOM更新后再显示对话框
      nextTick(() => {
        dialog.visible = true;
      });
    };

    // 编辑按钮操作
    const handleUpdate = async (row: OrderVO) => {
      dialog.title = "修改订单";
      // 确保对话框状态先重置为false，强制组件重新渲染
      dialog.visible = false;

      try {
        const res = await getOrderInfo(row.orderId || 0);
        if (res.data) {
          currentOrder.value = res.data;
          // 使用nextTick确保DOM更新后再显示对话框
          nextTick(() => {
            dialog.visible = true;
          });
        }
      } catch (error) {
        handleLoadError(error, "订单详情");
      }
    };

    // 查看订单详情
    const handleView = (row: OrderVO) => {
      // 使用工具方法打开新标签页
      openTagByName(
        router,
        "AttendanceOrderDetail",
        `订单详情-${row.orderCode}`,
        { id: row.orderId },
        {
          activeMenu: "/attendance/order",
          dynamicLevel: 3
        }
      );
    };

    // 删除按钮操作
    const handleDelete = async (row: OrderVO) => {
      try {
        await ElMessageBox.confirm(`是否确认删除订单"${row.orderCode}"?`, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        });

        await deleteOrder(row.orderId || 0);
        ElMessage.success("删除成功");
        getList();
      } catch (error: any) {
        if (error !== "cancel") {
          handleLoadError(error, "删除订单");
        }
      }
    };

    // 导出按钮操作
    const handleExport = async () => {
      try {
        await ElMessageBox.confirm("确认导出所有订单数据吗？", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        });

        const _res = await exportOrder(queryParams); // 使用_前缀表示未使用变量
        // 实现导出逻辑
        ElMessage.success("导出成功");
      } catch (error: any) {
        if (error !== "cancel") {
          handleLoadError(error, "导出订单");
        }
      }
    };

    // 初始化
    onMounted(() => {
      getList();
      fetchProjectOptions();
      fetchSupplierOptions();
    });

    return {
      // 数据
      queryParams,
      orderList,
      loading,
      total,
      currentOrder,
      statusOptions,
      projectOptions,
      supplierOptions,

      // 对话框状态
      dialog,

      // 引用
      queryRef,

      // 方法
      getList,
      handleQuery,
      resetQuery,
      handleAdd,
      handleUpdate,
      handleView,
      handleDelete,
      handleExport,
      getStatusType,
      formatAmount,

      // 图标
      Plus,
      Download,
      Search,
      Refresh,
      Edit,
      View,
      Delete
    };
  }
});
</script>

<style lang="scss" scoped>
.order-container {
  .box-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .title {
        font-size: 18px;
        font-weight: bold;
      }

      .right-button {
        display: flex;
        gap: 10px;
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
}
</style>
